/**
 * 封装axios对象
 */
// 导入axios
import axios from 'axios'

// 导入store
import store from '@/store'

// 导入路由模块
import router from '@/router'

// 导入大数字的转化
import jsonBigInt from 'json-bigint'

const request = axios.create({
    baseURL: 'http://toutiao-app.itheima.net',
    transformResponse: [function(data) {
        try {
            return jsonBigInt.parse(data)
        } catch (error) {
            return data
        }
    }]
})

// 配置请求拦截器
request.interceptors.request.use(config => {
    if (store.state.user) {
        config.headers.Authorization = 'Bearer ' + store.state.user.token
    }
    return config
}, error => {
    return Promise.reject(error)
})


// 配置响应拦截器
request.interceptors.response.use(response => {
    return response
}, async error => {
    console.dir(error);
    // 判断是否是401
    if (error.response && error.response.status === 401) {
        // 判断当前是否有刷新token
        if (!store.state.user || !store.state.user.refresh_token) {
            return router.push("/login");
        }
        try {
            let { data: res } = await axios({
                url: 'http://toutiao-app.itheima.net/v1_0/authorizations',
                method: 'PUT',
                headers: {
                    Authorization: 'Bearer ' + store.state.user.refresh_token
                }
            })
            console.log('刷新成功');
            store.commit('setUser', {
                token: res.data.token,
                refresh_token: store.state.user.refresh_token
            })

            // 发送错误之前的请求
            request(error.config)
        } catch (error) {
            console.log("请求刷线 token 失败", err);
            router.push("/login");
        }
    }


    return Promise.reject(error)

})
export default request